package org.x.user.service.impl;


import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.x.common.config.BusinessException;
import org.x.user.dto.AssignAclsDTO;
import org.x.user.mapper.SysAclMapper;
import org.x.user.mapper.SysRoleMapper;
import org.x.user.service.ISysRoleAclService;
import org.x.user.entity.SysRoleAclEntity;
import org.x.user.mapper.SysRoleAclMapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

/**
 * 角色权限关联表 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
public class SysRoleAclServiceImpl extends ServiceImpl<SysRoleAclMapper, SysRoleAclEntity> implements ISysRoleAclService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysAclMapper sysAclMapper;
    @Autowired
    private SysRoleAclMapper sysRoleAclMapper;

    @Override
    public int assignAcls(AssignAclsDTO assignAclsDTO) {
        //校验角色存在性
        if(sysRoleMapper.selectOneById(assignAclsDTO.getRoleId()) == null){
            throw new BusinessException("角色不存在");
        }
        //校验权限点有效性
        for(Long aclId : assignAclsDTO.getAclIds()){
            if(sysAclMapper.selectOneById(aclId) == null){
                throw new BusinessException("权限点不存在");
            }
        }

        //删除角色权限点关系
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SysRoleAclEntity::getRoleId, assignAclsDTO.getRoleId());
        sysRoleAclMapper.deleteByQuery(queryWrapper);

        SysRoleAclEntity sysRoleAclEntity = new SysRoleAclEntity();
        sysRoleAclEntity.setRoleId(assignAclsDTO.getRoleId());
        int count = 0;
        for(Long aclId : assignAclsDTO.getAclIds()){
            sysRoleAclEntity.setAclId(aclId);
            sysRoleAclMapper.insert(sysRoleAclEntity);
            count++;
        }
        return count;
    }
}